﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TestUpload.FileTransferServiceRef;

namespace TestUpload
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            this.cmbDocTypeUp.Items.Add("SermonAudio");
            this.cmbDocTypeUp.Items.Add("Attachment");
            this.cmbDocTypeUp.SelectedIndex = 0;

            this.cmbDocTypeDown.Items.Add("SermonAudio");
            this.cmbDocTypeDown.Items.Add("Attachment");
            this.cmbDocTypeDown.SelectedIndex = 0;
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.textBox1.Text = openFileDialog1.FileName;
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                // get some info about the input file
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(textBox1.Text);

                // show start message
                Console.WriteLine("Starting uploading " + fileInfo.Name);
                Console.WriteLine("Size : " + fileInfo.Length);

                // open input stream
                using (System.IO.FileStream stream = new System.IO.FileStream(textBox1.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    using (StreamWithProgress uploadStreamWithProgress = new StreamWithProgress(stream))
                    {
                        uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged;

                        // start service client
                        FileTransferServiceClient client = new FileTransferServiceClient("BasicHttpBinding_FileTransferService");

                        DocumentType docType = cmbDocTypeUp.SelectedIndex == 0 ? DocumentType.SermonAudio : DocumentType.Attachment;
                        UploadFileRequest uploadRequest = new UploadFileRequest(docType, fileInfo.Name, stream.Length, (int)numDocIDUp.Value, uploadStreamWithProgress);
                        // upload file
                        client.UploadFile(uploadRequest);

                        //LogText("Done!");

                        // close service client
                        client.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception : " + ex.Message);
                //if (ex.InnerException != null) LogText("Inner Exception : " + ex.InnerException.Message);
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }
        }

        void uploadStreamWithProgress_ProgressChanged(object sender, StreamWithProgress.ProgressChangedEventArgs e)
        {
            if (e.Length != 0)
            {
                progressBar1.Value = (int)(e.BytesRead * 100 / e.Length);
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            try
            {
                // start service client
                FileTransferServiceClient client = new FileTransferServiceClient("BasicHttpBinding_FileTransferService");

                //LogText("Start");



                // get stream from server                
                DocumentType docType = cmbDocTypeDown.SelectedIndex == 0 ? DocumentType.SermonAudio : DocumentType.Attachment;
                int docID = (int)numDocIDDown.Value;
                
                DownloadFileRequest downRequest = new DownloadFileRequest(docType, docID);
                DownloadFileResponse downResponse = client.DownloadFile(downRequest);

                // kill target file, if already exists
                string filePath = System.IO.Path.Combine("C:\\Down", downResponse.FileName);
                if (System.IO.File.Exists(filePath)) System.IO.File.Delete(filePath);

                // write server stream to disk
                using (System.IO.FileStream writeStream = new System.IO.FileStream(filePath, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write))
                {
                    int chunkSize = 2048;
                    byte[] buffer = new byte[chunkSize];

                    do
                    {
                        // read bytes from input stream
                        int bytesRead = downResponse.FileByteStream.Read(buffer, 0, chunkSize);
                        if (bytesRead == 0) break;

                        // write bytes to output stream
                        writeStream.Write(buffer, 0, bytesRead);

                        // report progress from time to time
                        progressBar1.Value = (int)(writeStream.Position * 100 / downResponse.Length);
                    } while (true);

                    // report end of progress
                    //LogText("Done!");

                    writeStream.Close();
                }

                // close service client
                downResponse.FileByteStream.Dispose();
                client.Close();
            }
            catch (Exception ex)
            {
                //LogText("Exception : " + ex.Message);
                //if (ex.InnerException != null) LogText("Inner Exception : " + ex.InnerException.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
    }
}
